<template>
  <div class="owner-add">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{ formTitle }}</span>
        </div>
      </template>
    <div class="form-container">
      <el-form 
          :model="ownerForm"
        :rules="rules" 
          ref="ownerFormRef"
        label-width="120px"
          :disabled="loading"
          v-loading="loading"
        >
        <el-form-item label="业主姓名" prop="name">
            <el-input v-model="ownerForm.name" placeholder="请输入业主姓名"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="ownerForm.gender">
              <el-radio label="男">男</el-radio>
              <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
          <el-form-item label="联系电话" prop="phoneNumber">
            <el-input v-model="ownerForm.phoneNumber" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="ownerForm.idCard" placeholder="请输入身份证号"></el-input>
        </el-form-item>
          <el-form-item label="职业" prop="profession">
            <el-input v-model="ownerForm.profession" placeholder="请输入职业"></el-input>
        </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="ownerForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input 
              v-model="ownerForm.remarks"
            type="textarea" 
            :rows="3" 
            placeholder="请输入备注信息"
          ></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm" :loading="submitting">提交</el-button>
            <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
    </el-card>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus';
import axios from 'axios';

export default {
  name: 'OwnerAdd',
  data() {
    // 验证身份证号
    const validateIdCard = (rule, value, callback) => {
      if (!value) {
        callback();
      } else {
        const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        if (reg.test(value)) {
        callback();
        } else {
          callback(new Error('请输入正确的身份证号'));
        }
      }
    };
    
    // 验证手机号
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback();
      } else {
        const reg = /^1[3-9]\d{9}$/;
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error('请输入正确的手机号'));
        }
      }
    };
    
    // 验证邮箱
    const validateEmail = (rule, value, callback) => {
      if (!value) {
        callback();
      } else {
        const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error('请输入正确的邮箱'));
        }
      }
    };
    
    return {
      formTitle: '添加业主',
      loading: false,
      submitting: false,
      ownerForm: {
        id: null,
        name: '',
        gender: '男',
        phoneNumber: '',
        idCard: '',
        profession: '',
        email: '',
        remarks: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入业主姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        phoneNumber: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { validator: validateIdCard, trigger: 'blur' }
        ],
        email: [
          { validator: validateEmail, trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    // 如果是编辑，则获取ID并加载数据
    const id = this.$route.query.id;
    if (id) {
      this.formTitle = '编辑业主';
      this.loadOwnerData(id);
    }
  },
  methods: {
    // 加载业主数据
    async loadOwnerData(id) {
      try {
        this.loading = true;
        const response = await axios.get(`/api/owners/${id}`);
        this.ownerForm = response.data;
      } catch (error) {
        console.error('Failed to load owner data:', error);
        ElMessage.error('加载业主数据失败');
      } finally {
        this.loading = false;
      }
    },
    
    // 提交表单
    async submitForm() {
      try {
        const valid = await this.$refs.ownerFormRef.validate();
        if (!valid) {
          ElMessage.error('表单验证失败，请检查必填项');
          return;
        }
        
        this.submitting = true;
        
        if (this.ownerForm.id) {
          // 更新业主
          await axios.put(`/api/owners/${this.ownerForm.id}`, this.ownerForm);
          ElMessage.success('编辑成功');
        } else {
          // 添加业主
          await axios.post('/api/owners', this.ownerForm);
          ElMessage.success('添加成功');
        }
        
        // 返回列表页
        this.goBack();
      } catch (error) {
        console.error('Failed to submit form:', error);
        ElMessage.error(error.response?.data?.message || '提交失败，请稍后重试');
      } finally {
        this.submitting = false;
      }
    },
    
    goBack() {
      this.$router.push('/property/personnel/owner');
    }
  }
};
</script>

<style scoped>
.owner-add {
  padding: 20px;
}
.form-container {
  max-width: 800px;
  margin: 0 auto;
}
</style>
